<template>
  <view>
    <view class="cinema-top">
      <view style="display: flex">
        <view>
          <uni-icons
              type="left"
              size="24"
              @click="goBack()"
              style="margin-right: 20rpx"
          ></uni-icons>
        </view>
        <view class="tops-item">
          <view class="cinema-img">
            <image :src="dataInfo.movieInfo.logo"></image>
          </view>
          <view class="cinema-info">
            <view class="top-name">{{ officeInfo.moviename }}</view>
            <view class="top-name">{{ officeInfo.edition }}</view>
            <view class="top-name">{{ officeInfo.filmName }}</view>
            <view class="list-tel">{{ officeInfo.cinemaname }}</view>
            <view class="list-tel">{{ officeInfo.roomname }}</view>
          </view>
        </view>
      </view>
    </view>

    <view class="cinema-main">
      <view class="support">
        <image
            src="https://picture-1326598115.cos.ap-nanjing.myqcloud.com/2025/09/248ea46173780a448c884c0aaa2a119910moive-no-close.png"></image>
        <text>不支持退票</text>
        <image
            src="https://picture-1326598115.cos.ap-nanjing.myqcloud.com/2025/09/248ea46173780a448c884c0aaa2a119910moive-no-close.png"
            style="margin-left: 60rpx"
        ></image>
        <text>不支持改签</text>
      </view>

      <view class="seat-item">
        <view class="seat-text">座位</view>
        <view class="seat-val">
          <text v-for="(value, index) in dataInfo.showInfo" :key="index"
          >{{ value.seatName }},
          </text
          >
        </view>
      </view>

      <view class="lines"></view>

      <view class="price-item">
        <view class="pirce-list">
          <view class="pirce-text"
          >票价合计(共{{ dataInfo.showInfo?.length || 0 }}张）
          </view
          >
          <view class="pirce-valss"
          >¥{{ dataInfo.originalPrice }}
          </view
          >
        </view>
      </view>
      <view class="lines"></view>
      <view class="lines"></view>

      <view class="ticket-notice">
        <view class="not-text">购票须知</view>
        <view class="not-list">
          <view class="list-num">1、</view>
          <view class="not-conot"
          >根据中国电影发行放映协会通知，影院需实名登记观众信息，以及体温测量，未佩戴口罩以及体温在37.3度以上不得入内。入场前请做好上诉准备，以免影响观影。
          </view
          >
        </view>
        <view class="not-list">
          <view class="list-num">2、</view>
          <view class="not-conot"
          >特价电影票，购买成功后将
            <text>不可退款、改签</text>
            。支付前务必确认影院、影片、场次准备无误。
          </view
          >
        </view>
        <view class="not-list">
          <view class="list-num">3、</view>
          <view class="not-conot"
          >
            <text>出票时间为9:00~23:30
            </text
            >
            ,支付完成后20~60分钟完成出票，非出票时间的订单需等待至出票时间方可出票。
          </view
          >
        </view>
        <view class="not-list">
          <view class="list-num">4、</view>
          <view class="not-conot"
          >若不能出票或者所选座位已售且不接受座位调整，订单将会在
            <text>24~72</text>
            小时内自动退款。
          </view
          >
        </view>
      </view>

    </view>

    <view class="congirm-boom-nav">
      <view class="nav-lefts">
        <text class="shiji">实际付款</text>
        <text class="units">￥</text>
        <text class="shiji-val">{{ dataInfo.originalPrice }}</text>
      </view>
      <view class="go-pay" @click="goPay">去支付</view>
    </view>

    <!-- 调座规则弹窗 -->
    <uni-popup
        v-model="show"
        mode="center"
        border-radius="20"
        width="600"
        :closeable="true"
    >
      <view class="rule-title">调座规则</view>
      <view class="rule-content">
        第三方服务商出票，由于出票过程存在时间差，可能存在已选座位被占情况。为了不耽误您的时间，我们将按照优先选取从（银幕中央-核心区域-边缘）的顺序为您调换座位。购买多张票将继续为您的座位保持连座。
      </view>
    </uni-popup>

    <!-- 订单提示弹窗 -->
    <su-popup
        v-model:show="showOrderPopup"
        type="center"
        :is-mask-click="false"
        :round="25"
        @close="handlePopupClose"
    >
      <view class="su-popup-content">
        <view class="order-popup-title">订单提示</view>
        <view class="order-popup-content">{{ orderPopupMessage }}</view>
        <view class="order-popup-buttons">
          <view class="cancel-btn" @click="cancelOrder">取消订单</view>
          <view class="continue-btn" @click="continuePayment">取消</view>
        </view>
      </view>
    </su-popup>

  </view>
</template>

<script setup>
import {reactive, ref} from 'vue';
import {onLoad} from '@dcloudio/uni-app';
import sheep from "@/sheep";

// 响应式数据
const show = ref(false);
const showOrderPopup = ref(false); // 修改为false，避免页面加载时自动打开
const orderPopupMessage = ref('');
const pendingOrderId = ref('');
const officeInfo = ref({});
const dataInfo = reactive({
  price: "",
  originalPrice: "",
  movieInfo: {},
  showInfo: [],
});
const cinemaId = ref(0);

// 生命周期钩子
onLoad((opt) => {
  console.log("opt", opt);
  const prm = JSON.parse(opt.prm);
  Object.assign(dataInfo.movieInfo, prm.movieInfo);
  cinemaId.value = prm.cinemaId.value;
  Object.assign(officeInfo.value, prm.officeInfo);
  dataInfo.showInfo = prm.showInfo;
  dataInfo.originalPrice = prm.price;
});

async function lockSeat() {
  try {
    let seatInfo = {
      seatIds: '',
      seatNames: ''
    }
    dataInfo.showInfo.map((item) => {
      seatInfo.seatNames += item.seatName + ',';
      seatInfo.seatIds += item.seatId + ',';
    })
    
    const result = await sheep.$api.xkMovie.lockSeat({
      opiId: officeInfo.value.opiid,
      seatIds: seatInfo.seatIds,
      seatNames: seatInfo.seatNames,
      cityCode: uni.getStorageSync('xk-map').id,
      movieId: dataInfo.movieInfo.id
    });
    
    console.log('lockSeat接口返回:', result);
    
    // 处理 code 为 9999 的情况 - 存在未支付订单
    if (result.code === 9999) {
      console.log('========== 检测到未支付订单(code:9999) ==========');
      console.log('完整返回数据:', JSON.stringify(result));
      console.log('result.data类型:', typeof result.data);
      console.log('result.data内容:', result.data);
      
      // 检查所有可能的订单号字段
      console.log('订单号字段检查:', {
        'data.orderNumber': result.data?.orderNumber,
        'data.orderId': result.data?.orderId,
        'data.id': result.data?.id,
        'data.outOrderNumber': result.data?.outOrderNumber
      });
      
      // 先设置订单信息 - 尝试多个可能的字段名
      // 优先使用 orderNumber（轩夸订单号），用于取消订单API
      const orderId = result.data?.orderNumber || 
                      result.data?.outOrderNumber || 
                      result.data?.orderId || 
                      result.data?.id || 
                      '';
      
      pendingOrderId.value = orderId;
      orderPopupMessage.value = result.msg || '您当前还有未支付的订单，不能重复下单!';
      
      console.log('提取的订单号:', orderId);
      console.log('设置后的 pendingOrderId.value:', pendingOrderId.value);
      
      if (!orderId) {
        console.error('❌ 警告: 未能从返回数据中获取到订单号！');
        console.error('请检查后端返回的数据结构是否包含 orderNumber 字段');
      } else {
        console.log('✅ 订单号设置成功');
      }
      console.log('================================================');
      
      // 延迟设置弹窗显示状态，确保DOM和响应式数据都已更新
      setTimeout(() => {
        showOrderPopup.value = true;
        console.log('弹窗状态已设置为true, showOrderPopup:', showOrderPopup.value);
        console.log('pendingOrderId:', pendingOrderId.value);
        console.log('orderPopupMessage:', orderPopupMessage.value);
      }, 100);
      return;
    }
    
    // 获取到订单号,跳转支付
    if (result.code === 200 && result.data && result.data.orderNumber) {
      console.log('锁座成功，跳转支付页面');
      showOrderPopup.value = false;
      sheep.$router.go('/pages/xk-movie/pay', {
        orderId: result.data.orderNumber,
      });
    } else {
      // 其他错误情况
      console.error('锁座失败:', result);
      uni.showToast({
        title: result.msg || '下单失败，请重试',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('lockSeat异常:', error);
    uni.showToast({
      title: '网络异常，请重试',
      icon: 'none'
    });
  }
}

// 获取未支付的订单
async function getUnpaid() {
  const result = await sheep.$api.xkMovie.getUnpaid()
  if (result.data) {
    pendingOrderId.value = result.data.orderNumber;
    orderPopupMessage.value = '您当前还有未支付的订单，不能重复下单!';
    showOrderPopup.value = true;
  }else{
    return result;
  }
}

// 去支付
async function goPay() {
  // 下单之前查询是否有订单未支付
  let result = await getUnpaid();
  if (result.code === 200) {
    // 锁定下单
    await lockSeat();
  }
}

// 取消订单
const cancelOrder = async () => {
  console.log('取消订单 - pendingOrderId.value:', pendingOrderId.value);
  
  // 验证订单号是否存在
  if (!pendingOrderId.value) {
    console.error('取消订单失败: 订单号为空');
    uni.showToast({
      title: '订单号不存在，无法取消',
      icon: 'none'
    });
    showOrderPopup.value = false;
    return;
  }
  
  try {
    console.log('调用取消订单接口，参数:', { orderNumber: pendingOrderId.value });
    
    const result = await sheep.$api.xkMovie.cancelOrder({
      orderNumber: pendingOrderId.value
    });
    
    console.log('取消订单接口返回:', result);
    
    if (result.code === 200) {
      sheep.$helper.toast('已取消订单');
      // 清空订单号
      pendingOrderId.value = '';
    } else {
      uni.showToast({
        title: result.msg || '取消订单失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('取消订单异常:', error);
    uni.showToast({
      title: '取消订单失败，请重试',
      icon: 'none'
    });
  } finally {
    showOrderPopup.value = false;
  }
};

// 继续支付
const continuePayment = () => {
  showOrderPopup.value = false;
  if (pendingOrderId.value) {
    // 如果有未支付的订单ID，跳转到支付页面 orderNumber
    sheep.$router.go('/pages/xk-movie/pay', {
      orderId: pendingOrderId.value,
    });
  }
};

// 弹窗关闭回调
const handlePopupClose = () => {
  console.log('弹窗关闭');
  showOrderPopup.value = false;
};

// 方法
const goBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};
</script>

<style lang="scss" scoped>
.cinema-top {
  background-color: #636775;
  padding: 90rpx 32rpx 70rpx 20rpx;
  position: relative;

  .tops-item {
    display: flex;
    align-items: center;
    z-index: 9999;
  }

  .cinema-img {
    width: 160rpx;
    height: 222rpx;

    image {
      width: 160rpx;
      height: 222rpx;
      border-radius: 20rpx;
    }
  }

  .cinema-info {
    margin-left: 30rpx;

    .top-name {
      color: #ffffff;
      font-size: 32rpx;
      font-weight: 600;
    }

    .list-tel {
      color: #d8d8dd;
      font-size: 24rpx;
      margin-top: 10rpx;
    }
  }
}

.cinema-main {
  position: absolute;
  top: 332rpx;
  left: 0;
  right: 0;
  background-color: #ffffff;
  border-radius: 30rpx 30rpx 0rpx 0rpx;
  padding-bottom: 120rpx;
}

.support {
  margin: 40rpx 32rpx 0rpx 32rpx;
  background-color: #ffefee;
  border-radius: 8rpx;
  padding: 22rpx 25rpx;
  display: flex;
  align-items: center;

  image {
    width: 28rpx;
    height: 28rpx;
  }

  text {
    color: #f03d38;
    font-size: 24rpx;
    margin-left: 12rpx;
  }
}

.seat-item {
  margin: 50rpx 32rpx 9rpx 32rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 28rpx;

  .seat-text {
    color: #636775;
  }

  .seat-val {
    color: #2d3039;
  }
}

.automatic-item {
  padding: 32rpx;
  display: flex;
  align-items: center;

  .aut-tops {
    display: flex;
    align-items: center;

    image {
      width: 28rpx;
      height: 28rpx;
      margin-left: 16rpx;
    }

    text {
      color: #636775;
      font-size: 28rpx;
    }
  }

  .aut-tips {
    margin-top: 4rpx;
    color: #fe602b;
    font-size: 24rpx;
  }
}

.lines {
  height: 20rpx;
  background-color: #f3f4f7;
}

.price-item {
  background-color: #ffffff;
  padding: 20rpx 32rpx;

  .pirce-list {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 0;
    font-size: 28rpx;

    .pirce-text {
      color: #636775;
    }

    .pirce-val {
      color: #2d3039;
    }

    .pirce-vals {
      color: #fe602b;
    }

    .pirce-valss {
      color: #fe602b;
      font-weight: 550;
    }
  }
}

.order-phone-item {
  padding: 20rpx 0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .pho-text {
    color: #636775;
    font-size: 29rpx;
  }

  .phone-tips {
    margin-top: 4rpx;
    color: #a6a8ae;
    font-size: 24rpx;
  }

  .phone-input {
    font-size: 28rpx;
    width: 32%;
  }
}

.ticket-notice {
  padding: 40rpx 56rpx 40rpx 32rpx;
  background-color: #ffffff;

  .not-text {
    color: #2d3039;
    font-size: 28rpx;
    font-weight: 550;
  }

  .not-list {
    display: flex;
    margin-top: 20rpx;
    color: #636775;
    font-size: 28rpx;

    text {
      color: #f03d38;
      font-weight: 550;
    }
  }
}

.agreement {
  display: flex;
  align-items: center;
  background-color: #f2f5fa;
  padding: 24rpx 30rpx;

  image {
    width: 32rpx;
    height: 32rpx;
  }

  text {
    color: #2d3039;
    font-size: 24rpx;
    margin-left: 10rpx;
  }
}

.congirm-boom-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 120rpx;
  z-index: 9999;
  padding-left: 48rpx;
  padding-right: 40rpx;

  .nav-lefts {
    display: flex;
    align-items: center;

    .shiji {
      color: #636775;
      font-size: 24rpx;
      margin-top: 4rpx;
    }

    .units {
      color: #fe602b;
      font-size: 28rpx;
      font-weight: 550;
      margin-left: 18rpx;
      margin-top: 4rpx;
    }

    .shiji-val {
      color: #fe602b;
      font-size: 42rpx;
      font-weight: 550;
    }
  }

  .go-pay {
    width: 230rpx;
    height: 92rpx;
    text-align: center;
    line-height: 92rpx;
    background-color: #fe602b;
    border-radius: 46rpx;
    color: #ffffff;
    font-size: 32rpx;
    font-weight: 600;
  }
}

.rule-title {
  text-align: center;
  padding-top: 30rpx;
  color: #292928;
  font-size: 36rpx;
  font-weight: 550;
}

.rule-content {
  padding: 35rpx 35rpx 50rpx 35rpx;
  color: #636775;
  font-size: 28rpx;
  line-height: 46rpx;
}

.su-popup-content {
  background-color: #ffffff;
  border-radius: 25rpx;
  overflow: hidden;
  min-width: 540rpx;
}

.order-popup-title {
  text-align: center;
  padding-top: 30rpx;
  color: #292928;
  font-size: 36rpx;
  font-weight: 550;
}

.order-popup-content {
  padding: 35rpx;
  color: #636775;
  font-size: 28rpx;
  line-height: 46rpx;
  text-align: center;
  min-height: 100rpx;
}

.order-popup-buttons {
  display: flex;
  border-top: 1rpx solid #f0f0f0;
}

.cancel-btn {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  color: #636775;
  font-size: 32rpx;
  border-right: 1rpx solid #f0f0f0;
}

.continue-btn {
  flex: 1;
  text-align: center;
  padding: 30rpx 0;
  color: #fe602b;
  font-size: 32rpx;
  font-weight: 550;
}
</style>
